package com.woniuxy.controller;


import com.woniuxy.commons.exception.LateException;
import com.woniuxy.commons.utile.OssTemplate;
import com.woniuxy.commons.utile.Result;
import com.woniuxy.controller.dto.ImgDto;
import com.woniuxy.controller.form.ShowrepairForm;
import com.woniuxy.service.RepairAttachmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Random;

/**
 * <p>
 * 附件表 前端控制器
 * </p>
 *
 * @author Keep it simple
 * @since 2022-06-28
 */
@RestController
@Api(tags = "文件上传接口")
@RequestMapping("/repairAttachment")
public class RepairAttachmentController {

    @Resource
    private RepairAttachmentService repairAttachmentService;


    @ApiOperation("获取文件上传的oss地址")
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(MultipartFile file) throws IOException {
        System.out.println("file.........");
        System.out.println(file);
        //原文件名
        String oldname = file.getOriginalFilename();
        String prefix = oldname.substring(oldname.lastIndexOf("."));
        Random random = new Random();
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        StringBuffer newname = new StringBuffer();
        for (int i = 0; i < 6; i++) {
            int number = random.nextInt(base.length());
            newname.append(base.charAt(number));
        }
        newname.append(prefix);
        String url = OssTemplate.fileUpload(newname.toString(), file.getInputStream(), "repairstage");
        if (url!=null){
            System.out.println(url);
            return Result.instance().setCode(200).setMessage("cg").setData(url);
        }
        throw new LateException(1006,"失败");
    }

    @ApiOperation("获取完工后的文件地址")
    @PostMapping("/ShowOss")
    public Result Oss(@RequestBody ShowrepairForm showrepairForm){
        System.out.println(showrepairForm);
        ImgDto getfilename = repairAttachmentService.getfilename(showrepairForm.getRepairNum());
        return Result.instance().setCode(200).setMessage("成功").setData(getfilename);
    }

}

